﻿using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

namespace EFCoreBest.Domain
{
    public class TestDbContext : DbContext
    {
        public TestDbContext(DbContextOptions options) : base(options)
        {
        }

        public virtual DbSet<Product> Products { get; set; }

        public virtual DbSet<User> Users { get; set; }

        public virtual DbSet<Order> Orders { get; set; }

        public virtual DbSet<OrderItem> OrderItems { get; set; }

        public virtual DbSet<Blog> Blogs { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            foreach (var entityType in modelBuilder.Model.GetEntityTypes())
            {
                if (entityType.ClrType.IsSubclassOf(typeof(Entity)))
                {
                    var builder = modelBuilder.Entity(entityType.ClrType);
                    builder.Property(nameof(Entity.CreateAt))
                        .HasDefaultValueSql("CURRENT_TIMESTAMP");
                }
            }

            var user = modelBuilder.Entity<User>();
            user.HasData(new User
            {
                Id = 1,
                Name = "yc",
            });

            var product = modelBuilder.Entity<Product>();
            //product.Property(x => x.UpdateAt)
            //    .hs
            //    .HasComputedColumnSql("CURRENT_TIMESTAMP");

            product.HasData(new[]
            {
                new Product
                {
                    Id = 1,
                    Name = "P1",
                    Price = 100M,
                    Stock = 10,
                },
                new Product
                {
                    Id = 2,
                    Name = "P2",
                    Price = 200M,
                    Stock = 10,
                },
                new Product
                {
                    Id = 3,
                    Name = "P3",
                    Price = 300M,
                    Stock = 10,
                },
            });

            var order = modelBuilder.Entity<Order>();
            order.HasData(new[]
            {
                new Order
                {
                    Id = 1,
                    UserId = 1
                },
            });

            var orderItems = modelBuilder.Entity<OrderItem>();
            orderItems.HasData(new[]
            {
                new OrderItem
                {
                    Id = 1,
                    ProductId = 1,
                    OrderId = 1,
                    Price = 100M,
                    Count = 2
                },
                new OrderItem
                {
                    Id = 2,
                    OrderId = 1,
                    ProductId = 2,
                    Price = 200M,
                    Count = 1
                }
            });
        }
    }
}